package com.hnichr.ump.talent.library.provider.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hnichr.ump.common.talent.library.entity.Train;
import com.hnichr.ump.common.talent.library.service.TrainService;
import com.hnichr.ump.talent.library.provider.SyncPolicyProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class TrainSyncPolicyProvider implements SyncPolicyProvider {
    private static final String KEY = "trainList";

    @Autowired
    private TrainService trainService;

    @Override
    public boolean support(JSONObject jsonObject) {
        return jsonObject.containsKey(KEY);
    }

    @Override
    @Transactional
    public void sync(String syncDate, JSONObject jsonObject) {
        JSONArray trainList = jsonObject.getJSONArray(KEY);
        if(CollectionUtils.isEmpty(trainList)){
            return;
        }
        for(Object trainObject:trainList){
            if(trainObject instanceof JSONObject){
                JSONObject trainJSONObject = (JSONObject) trainObject;
                Train train = new Train();
                train.setId(trainJSONObject.getString("id"));
                train.setDelFlag(trainJSONObject.getBoolean("delFlag"));
                train.setUserId(trainJSONObject.getString("userId"));
                if(trainJSONObject.containsKey("createTime")){
                    train.setOrginalCreateTime(new Date(trainJSONObject.getLong("createTime")));
                }
                if(trainJSONObject.containsKey("updateTime")){
                    train.setOrginalUpdateTime(new Date(trainJSONObject.getLong("updateTime")));
                }

                if(trainJSONObject.containsKey("startTime")){
                    train.setStartTime(new Date(trainJSONObject.getLong("startTime")));
                }

                if(trainJSONObject.containsKey("endTime")){
                    train.setEndTime(new Date(trainJSONObject.getLong("endTime")));
                }

                train.setMechanismName(trainJSONObject.getString("mechanismName"));
                train.setCurriculum(trainJSONObject.getString("curriculum"));
                train.setResumeId(trainJSONObject.getString("resumeId"));
                train.setSyncDate(syncDate);
                trainService.merge(train);
            }
        }
    }
}
